I'm trying to run a js function using parameters passed into the template via jinja, where item contains strings as follows:
item.id = 'item1'
item.indicator = 'yes' #or no
Template code:
{% for item in items %}
<!--The error is thrown by the line directly below!-->
<div class='qitem' id='{{item.id}}' onclick = change_background('{{item.indicator}}', '{{item.id}}')></div>
{% endfor %}
<script>
function change_background(indicator, id){
if (indicator == 'yes'){
document.getElementById(id).style.background='lightgreen';
}else{
document.getElementById(id).style.background='pink';
</script>
In the culpable line in my code, '{{item.indicator}}' is red, and the first ' is underlined in vscode.
The code works despite this, if only ONE argument it used as follows:
change_background('{{item.indicator}}') (with corresponding function adjusted accordingly), but does not work if I try to use two arguments.
The order of the arguments doesn't seem to matter. Neither does using "{{}}" instead of '{{}}'.
Additionally, if I attempt to run two functions onclick:
<div class='qitem' id='{{item.id}}' onclick = make_green('{{item.id}}'); increment_click('{{item.indicator}}')>
only the first executes, and the second is ignored without any errors being thrown!
I've searched on here and elsewhere. I don't really want to jsonify the data I pass in to the template. I feel as though there's a nuance I'm missing when using jinja.
The nuance here is simply your use of JavaScript in HTML.
You'll need
onclick="change_background('{{item.indicator}}', '{{item.id}}')"
instead of
onclick = change_background('{{item.indicator}}', '{{item.id}}')>
to properly wrap the JavaScript segment in quotes.
Additionally, if I attempt to run two functions onclick:
<div class='qitem' id='{{item.id}}' onclick = > make_green('{{item.id}}'); increment_click('{{item.indicator}}')>
Same thing here.
onclick="make_green('{{item.id}}');increment_click('{{item.indicator}}')"